package edu.gyc.okshiro.shiro;

import edu.gyc.okshiro.model.Myuser;
import edu.gyc.okshiro.service.MyuserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class MyuserRealm extends AuthorizingRealm {
    @Autowired
    private MyuserService myuserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("开始身份认证...");
        String name=(String)authenticationToken.getPrincipal();

        Myuser myuser=myuserService.lambdaQuery().eq(Myuser::getUsername,name).one();
        if (myuser == null) {
           return null;
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(myuser.getUsername(), myuser.getPassword(), getName());

        //防止密码泄露
        myuser.setPassword("");
        SecurityUtils.getSubject().getSession().setAttribute("user",myuser);
        //返回info后，shiro会比较authenticationToken与info里的密码，若有异常就会抛出
        return info;
    }
}
